package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.health.constants.MessageConstant;
import com.itheima.health.constants.RedisConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * @ClassName SetmealMobileController
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/9/16 9:51
 * @Version V1.0
 */
@RestController
@RequestMapping(value = "/setmeal")
public class SetmealMobileController {

    @Reference
    SetmealService setmealService;

    @Autowired
    JedisPool jedisPool;

    // 查询所有套餐
    @RequestMapping(value = "/getSetmeal")
    public Result getSetmeal() {
        List<Setmeal> list = null;
        try {
            list = JSON.parseArray(jedisPool.getResource().hget(RedisConstant.ALL_PACKAGE_NAME,11+""),Setmeal.class);
            if (list == null) {
                list = setmealService.findAll();
                jedisPool.getResource().hset(RedisConstant.ALL_PACKAGE_NAME,11+"",JSON.toJSON(list).toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            list = setmealService.findAll();
        }finally {
            if (list != null && list.size() > 0) {
                return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, list);
            } else {
                return new Result(false, MessageConstant.GET_SETMEAL_LIST_FAIL);
            }
        }
    }

    // 使用套餐id，查询套餐的详情信息
    @RequestMapping(value = "/findById")
    public Result findById(Integer id) {
        Setmeal setmeal = null;
        try {
            setmeal = new Setmeal();
            setmeal = JSON.parseObject(jedisPool.getResource().hget(RedisConstant.PACKAGE_NAME,id.toString()),Setmeal.class);
            if (setmeal == null) {
                setmeal = setmealService.findById(id);
                jedisPool.getResource().hset(RedisConstant.PACKAGE_NAME,id.toString(),JSON.toJSON(setmeal).toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            setmeal = setmealService.findById(id);
        }finally {
            if (setmeal != null) {
                return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
            } else {
                return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
            }
        }
    }
}
